/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mia;

import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Greg Jarzab <greg.jarzab@gmail.com>
 */
public class QueryLoader
{

    private QueryHandler handler;

    public QueryLoader()
    {
        handler = new QueryHandler();
    }

    public ArrayList<Query> GetQueries()
    {
        ArrayList<Query> queryList = new ArrayList<Query>();
        for ( String current : handler.GetQueryData() )
        {
            // Remove extra whitespace from queries.
            queryList.add( new Query( current.replaceAll( "\\s+", " " ).replaceAll( "[\\r\\n]", " " ) ) );
        }

        return queryList;
    }

    public boolean LoadQueries( String filename )
    {
        try
        {
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();   // Create a new SAX Parser
            parser.parse( filename, handler );
        } catch ( Exception e )
        {
            System.err.println( "Error while parsing " + filename );
            return false;
        }
        return true;
    }

    private class QueryHandler extends DefaultHandler
    {
        private boolean inQuery = false;
        private StringBuffer currentString = null;
        private ArrayList<String> queries = null;

        public QueryHandler()
        {
            currentString = new StringBuffer();
            queries = new ArrayList<String>();
        }

        public ArrayList<String> GetQueryData()
        {
            return queries;
        }

        @Override
        public void startElement( String namespaceUri,
                                  String localName,
                                  String qualifiedName,
                                  Attributes attributes ) throws SAXException
        {
            if ( qualifiedName.equals( "query" ) )
            {
                inQuery = true;
                currentString.setLength( 0 );
            }
        }

        @Override
        public void endElement( String namespaceUri,
                                String localName,
                                String qualifiedName ) throws SAXException
        {
            if ( qualifiedName.equals( "query" ) )
            {
                inQuery = false;
                queries.add( currentString.toString() );
            }
        }

        @Override
        public void characters( char[] chars,
                                int startIndex,
                                int endIndex )
        {
            if ( inQuery )
            {
                currentString.append( new String( chars, startIndex, endIndex ).trim() );
            }
        }
    }
}
